import Vue from 'vue';
import VueRouter from 'vue-router'  //导入vue-router模块
Vue.use(VueRouter); //在模块化开发中需要手动安装到vue中

import app from './App.vue'
import router from './router' //导入路由

import MintUI from 'mint-ui'  //导入mintui所以的组件
import 'mint-ui/lib/style.css'

Vue.use(MintUI);


import './lib/mui/dist/css/mui.css'  //导入mui
import './lib/mui/dist/css/icons-extra.css' //导入字体图标拓展的css，mui.css中没有

import VueResource from 'vue-resource'

Vue.use(VueResource);

import VuePreview from 'vue-preview'

Vue.use(VuePreview);

import Vuex from 'vuex'

Vue.use(Vuex);

const shoppingCarts = JSON.parse(localStorage.getItem('shoppingCarts') || '[]');
const store = new Vuex.Store({
    state: {
        shoppingCarts: shoppingCarts
    },
    mutations: {
        addGoods(state, goods) {
            var goodIndex = state.shoppingCarts.findIndex(item => item.id === goods.id);
            if (goodIndex === -1) {
                state.shoppingCarts.push(goods);
            } else {
                state.shoppingCarts[goodIndex].count += parseInt(goods.count);
            }
            localStorage.setItem('shoppingCarts', JSON.stringify(state.shoppingCarts));
        },
        delGoods(state, goodsId) {
            state.shoppingCarts.splice(state.shoppingCarts.findIndex(item => parseInt(item.id) === goodsId), 1);
            localStorage.setItem('shoppingCarts', JSON.stringify(state.shoppingCarts));
        },
        updateGoods(state, goods) {
            state.shoppingCarts.some(item => {
                if (parseInt(item.id) === goods.id) {
                    item.count = parseInt(goods.count);
                    localStorage.setItem('shoppingCarts', JSON.stringify(state.shoppingCarts));
                    return true
                }
            })
        }
    },
    getters: {
        totalCount: function (state) {
            var c = 0;
            state.shoppingCarts.forEach(item => {
                c += item.count;
            });
            return c;
        },
        getGoodsCount(state) {
            var obj = {};
            state.shoppingCarts.forEach(item => {
                obj[item.id] = item.count;
            });
            return obj
        }
    }
});

Vue.filter('DateFormat', function (data) {
    const dt = new Date(data);
    const h = dt.getHours().toString().padStart(2, '0'); //时
    const m = dt.getMinutes().toString().padStart(2, '0'); //分
    const s = dt.getSeconds().toString().padStart(2, '0'); //秒
    const Y = dt.getFullYear(); //年
    const M = (dt.getMonth() + 1).toString().padStart(2, '0');//月，因为从0-11所以加1
    const D = dt.getDate().toString().padStart(2, '0'); //日，getDay是获得星期几
    return `${Y}-${M}-${D} ${h}:${m}:${s}`;
}); //时间格式化

let vm = new Vue({
    el: '#app',
    data: {
        msg: 'hello'
    },
    render: function (createElement) {
        return createElement(app);
    },
    router: router,
    store: store
});

